<?php

namespace cf;

class param
{
   static public function exist($nm) 
   {
      return self::findByName($nm,$_GET)!==false || self::findByName($nm,$_POST)!==false;
   }

   static public function get($nm) 
   {
      $v = self::findByName($nm,$_GET);
      if ($v === false) {
         $v = self::findByName($nm,$_POST);
      }
      if ($v === false) {
         throw new \Exception("Param [$nm] not found");
      }
      return $v;
   }

   /** @return null if param not exists or is not valid number */
   static public function asInt($nm)
   {
      if (self::exist($nm))
      {
         $val = self::get($nm);
         if (!is_null($val) && !is_array($val) && strlen($val))
         {
            return intval($val);
         }
      }
      return null;
   }

   /** @return null if param not exists or empty string */
   static public function asString($nm)
   {
      if (self::exist($nm))
      {
         $s = self::get($nm);
         if (strlen($s))
         {
            return $s;
         }
      }
      return null;
   }

   static public function toString() 
   {
      $s = "GET:\n";
      foreach ($_GET as $nm => $val) 
      {
         $s .= "$nm=" . (is_array($val) ? implode(',',$val) : $val) . ";\n";
      }
      $s .= "POST:\n";
      foreach ($_POST as $nm => $val) 
      {
         $s .= "$nm=" . (is_array($val) ? implode(',',$val) : $val) . ";\n";
      }
      return $s;
   }

   static public function toArray() 
   {
      return array_merge($_GET, $_POST);
   }

   static public function check($nm1/*,...*/) 
   {
      $args = func_get_args();
      foreach ($args as $arg) 
      {
         if (!self::exist($arg)) 
         {
            throw new \Exception(
               "Parameter [$arg] not found among [".
               self::toString().
               "] passed to [" . 
               $_SERVER['PHP_SELF'].
               "]"
            );
         }
      }
   }

   static public function present() 
   {
      return !(empty($_GET) && empty($_POST));
   }


   static private function findByName($nm, &$params)
   {
      foreach ($params as $k => $v) {
         if (!strcasecmp($nm,$k)) {
            return $v;
         }
      }
      return false;
   }
};

?>